/**
 * 基于uni-app的HTTP请求工具库
 * 支持灵活的配置、拦截器、错误处理等功能
 */

// 默认配置
const defaultConfig = {
    baseURL: 'https://admin.iepsy.com/api/sa',
    timeout: 10000,
    header: {
        'Content-Type': 'application/json'
    }
}

class HttpRequest {
    constructor(config = {}) {
        this.config = { ...defaultConfig, ...config }
        this.interceptors = {
            request: [],
            response: []
        }
    }

    /**
     * 添加请求拦截器
     * @param {Function} fulfilled 成功回调
     * @param {Function} rejected 失败回调
     */
    addRequestInterceptor(fulfilled, rejected) {
        this.interceptors.request.push({ fulfilled, rejected })
    }

    /**
     * 添加响应拦截器
     * @param {Function} fulfilled 成功回调
     * @param {Function} rejected 失败回调
     */
    addResponseInterceptor(fulfilled, rejected) {
        this.interceptors.response.push({ fulfilled, rejected })
    }

    /**
     * 处理请求拦截器
     * @param {Object} config 请求配置
     */
    async processRequestInterceptors(config) {
        let processedConfig = config
        for (const interceptor of this.interceptors.request) {
            try {
                if (interceptor.fulfilled) {
                    processedConfig = await interceptor.fulfilled(processedConfig)
                }
            } catch (error) {
                if (interceptor.rejected) {
                    return interceptor.rejected(error)
                }
                throw error
            }
        }
        return processedConfig
    }

    /**
     * 处理响应拦截器
     * @param {Object} response 响应数据
     */
    async processResponseInterceptors(response) {
        let processedResponse = response
        for (const interceptor of this.interceptors.response) {
            try {
                if (interceptor.fulfilled) {
                    processedResponse = await interceptor.fulfilled(processedResponse)
                }
            } catch (error) {
                if (interceptor.rejected) {
                    return interceptor.rejected(error)
                }
                throw error
            }
        }
        return processedResponse
    }

    /**
     * 合并请求头
     * @param {Object} defaultHeaders 默认请求头
     * @param {Object} customHeaders 自定义请求头
     */
    mergeHeaders(defaultHeaders = {}, customHeaders = {}) {
        const headers = { ...defaultHeaders, ...customHeaders }
        
        // 过滤掉空值的header
        Object.keys(headers).forEach(key => {
            if (headers[key] === null || headers[key] === undefined || headers[key] === '') {
                delete headers[key]
            }
        })
        
        return headers
    }

    /**
     * 处理请求数据
     * @param {*} data 请求数据
     * @param {String} contentType 内容类型
     */
    processRequestData(data, contentType) {
        if (!data) return {}
        
        // 根据Content-Type处理数据
        if (contentType && contentType.includes('application/json')) {
            return typeof data === 'string' ? data : JSON.stringify(data)
        }
        
        if (contentType && contentType.includes('application/x-www-form-urlencoded')) {
            if (typeof data === 'object') {
                return Object.keys(data)
                    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
                    .join('&')
            }
        }
        
        return data
    }

    /**
     * 核心请求方法
     * @param {Object} options 请求选项
     */
    async request(options = {}) {
        // 合并配置
        let config = {
            url: options.url || '',
            method: (options.method || 'GET').toUpperCase(),
            data: options.data || {},
            header: this.mergeHeaders(this.config.header, options.header),
            timeout: options.timeout || this.config.timeout,
            dataType: options.dataType || 'json',
            responseType: options.responseType || 'text'
        }

        // 处理完整URL
        if (!config.url.startsWith('http')) {
            config.url = this.config.baseURL + config.url
        }

        // 处理请求拦截器
        try {
            config = await this.processRequestInterceptors(config)
        } catch (error) {
            return Promise.reject(error)
        }

        // 处理请求数据
        if (config.method !== 'GET' && config.data) {
            const contentType = config.header['Content-Type'] || config.header['content-type']
            config.data = this.processRequestData(config.data, contentType)
        }

        // 打印请求日志
        console.log('HTTP请求:', {
            url: config.url,
            method: config.method,
            header: config.header,
            data: config.data
        })

        return new Promise((resolve, reject) => {
            uni.request({
                ...config,
                success: async (res) => {
                    console.log('HTTP响应:', {
                        url: config.url,
                        statusCode: res.statusCode,
                        header: res.header,
                        data: res.data
                    })

                    try {
                        // 处理响应拦截器
                        const processedResponse = await this.processResponseInterceptors(res)
                        resolve(processedResponse)
                    } catch (error) {
                        reject(error)
                    }
                },
                fail: (error) => {
                    console.error('HTTP请求失败:', {
                        url: config.url,
                        error: error
                    })
                    
                    const errorInfo = {
                        message: '网络请求失败',
                        code: 'NETWORK_ERROR',
                        config: config,
                        error: error
                    }
                    
                    reject(errorInfo)
                }
            })
        })
    }

    // 便捷方法
    get(url, params = {}, options = {}) {
        // GET请求将参数拼接到URL
        if (Object.keys(params).length > 0) {
            const queryString = Object.keys(params)
                .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
                .join('&')
            url += (url.includes('?') ? '&' : '?') + queryString
        }
        
        return this.request({
            url,
            method: 'GET',
            ...options
        })
    }

    post(url, data = {}, options = {}) {
        return this.request({
            url,
            method: 'POST',
            data,
            ...options
        })
    }

    put(url, data = {}, options = {}) {
        return this.request({
            url,
            method: 'PUT',
            data,
            ...options
        })
    }

    delete(url, data = {}, options = {}) {
        return this.request({
            url,
            method: 'DELETE',
            data,
            ...options
        })
    }

    patch(url, data = {}, options = {}) {
        return this.request({
            url,
            method: 'PATCH',
            data,
            ...options
        })
    }
}

// 创建默认实例
const http = new HttpRequest()

// 添加默认的请求拦截器 - 自动添加token
http.addRequestInterceptor(
    (config) => {
        const token = uni.getStorageSync('token')
        if (token && token.trim() !== '') {
            config.header = config.header || {}
            config.header['token'] = token
        }
        return config
    },
    (error) => {
        console.error('请求拦截器错误:', error)
        return Promise.reject(error)
    }
)

// 添加默认的响应拦截器 - 统一处理业务逻辑
http.addResponseInterceptor(
    (response) => {
        const { statusCode, data } = response
        
        // HTTP状态码检查
        if (statusCode !== 200) {
            const error = {
                message: `HTTP错误 ${statusCode}`,
                code: statusCode,
                response: response
            }
            
            uni.showToast({
                title: error.message,
                icon: 'none'
            })
            
            return Promise.reject(error)
        }
        
        // 业务逻辑检查 - 增加空数据处理
        if (data === null || data === undefined || data === '') {
            // 处理空数据情况
            const error = {
                message: '请求成功但返回数据为空',
                code: 'EMPTY_DATA',
                response: response
            }
            
            return Promise.reject(error)
        }
        
        if (typeof data === 'object') {
            if (data.code === 0) {
                // 成功
                return data.data
            } else {
                // 业务失败
                const error = {
                    message: data.msg || '请求失败',
                    code: data.code,
                    response: response
                }
                
                uni.showToast({
                    title: error.message,
                    icon: 'none'
                })
                
                return Promise.reject(error)
            }
        }
        
        // 返回原始数据
        return data
    },
    (error) => {
        console.error('响应拦截器错误:', error)
        
        // 网络错误处理
        if (error.code === 'NETWORK_ERROR') {
            uni.showToast({
                title: '网络连接失败',
                icon: 'none'
            })
        }
        
        return Promise.reject(error)
    }
)

// 导出实例、类和配置
export default http
export { HttpRequest, defaultConfig }